<?php
// 引入头部
require_once 'includes/header.php';

// 获取所有商品分类
$categories = Database::fetchAll("SELECT * FROM categories ORDER BY sort ASC");

// 获取所有上架商品
$products = Database::fetchAll("SELECT p.*, c.name as category_name 
                              FROM products p 
                              JOIN categories c ON p.category_id = c.id 
                              WHERE p.status = 1 
                              ORDER BY p.category_id, p.id");

// 处理会员搜索请求
$phone_search = '';
$cash_phone_search = '';
$member_info = null;
$cash_member_info = null;
$search_error = '';
$cash_search_error = '';
$order_result = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取请求类型
    $search_type = $_POST['search_type'] ?? '';
    
    // 处理结账请求
    if ($search_type === 'checkout') {
        $payment_method = $_POST['payment_method'] ?? '';
        $member_id = $_POST['member_id'] ?? '';
        $remark = $_POST['remark'] ?? '';
        
        if (empty($payment_method)) {
            $order_result = [
                'success' => false,
                'message' => '请选择支付方式'
            ];
        } else {
            try {
                // 获取当前用户ID（收银员ID）
                $cashier_id = $current_user ? $current_user['id'] : 1;
                
                // 获取购物车信息
                $session_id = session_id();
                $cart_items = Database::fetchAll("SELECT c.*, p.name as product_name, p.price 
                                                FROM cart_items c 
                                                JOIN products p ON c.product_id = p.id 
                                                WHERE c.session_id = ?", [$session_id]);
                
                if (empty($cart_items)) {
                    $order_result = [
                        'success' => false,
                        'message' => '购物车为空，无法结账'
                    ];
                } else {
                    // 开始事务
                    $pdo = Database::getInstance();
                    $pdo->beginTransaction();
                    
                    try {
                        // 计算总价
                        $total_price = 0;
                        foreach ($cart_items as $item) {
                            $total_price += $item['price'] * $item['quantity'];
                        }
                        
                        // 设置实际价格（直接等于总价，不再考虑优惠券）
                        $actual_price = $total_price;
                        $discount_price = 0;
                        
                        // 生成订单号
                        $order_no = 'POS' . date('YmdHis') . rand(1000, 9999);
                        
                        // 获取最后的取餐号
                        $last_queue = Database::fetch("SELECT MAX(queue_number) as max_queue FROM orders WHERE DATE(created_at) = CURDATE()");
                        $queue_number = ($last_queue && isset($last_queue['max_queue'])) ? ($last_queue['max_queue'] + 1) : 1;
                        
                        // 验证会员余额（如果是余额支付）
                        if ($payment_method === 'balance' && !empty($member_id)) {
                            $member = Database::fetch("SELECT * FROM users WHERE id = ? AND role = 'member'", [$member_id]);
                            
                            if (!$member) {
                                throw new Exception('会员不存在');
                            }
                            
                            if ($member['balance'] < $actual_price) {
                                throw new Exception('会员余额不足');
                            }
                            
                            // 扣除会员余额
                            Database::query("UPDATE users SET balance = balance - ? WHERE id = ?", [$actual_price, $member_id]);
                        }
                        
                        // 创建订单
                        $order_data = [
                            'order_no' => $order_no,
                            'user_id' => !empty($member_id) ? $member_id : null,
                            'queue_number' => $queue_number,
                            'total_price' => $total_price,
                            'discount_price' => $discount_price,
                            'actual_price' => $actual_price,
                            'payment_method' => $payment_method,
                            'status' => 'cooking',
                            'cashier_id' => $cashier_id,
                            'remark' => $remark
                        ];
                        
                        // 插入订单
                        $order_id = Database::insert('orders', $order_data);
                        
                        // 插入订单项
                        foreach ($cart_items as $item) {
                            $item_data = [
                                'order_id' => $order_id,
                                'product_id' => $item['product_id'],
                                'product_name' => $item['product_name'],
                                'price' => $item['price'],
                                'quantity' => $item['quantity'],
                                'subtotal' => $item['price'] * $item['quantity'],
                                'status' => 'pending'
                            ];
                            
                            Database::insert('order_items', $item_data);
                        }
                        
                        // 添加会员积分（如果有会员）
                        if (!empty($member_id)) {
                            // 获取积分比例（假设1元=1积分）
                            $points_ratio = 1;
                            
                            // 计算获得的积分
                            $earned_points = floor($actual_price * $points_ratio);
                            
                            if ($earned_points > 0) {
                                // 更新会员积分
                                Database::query("UPDATE users SET points = points + ? WHERE id = ?", [$earned_points, $member_id]);
                                
                                // 记录积分明细
                                Database::insert('points_log', [
                                    'user_id' => $member_id,
                                    'points' => $earned_points,
                                    'description' => "订单消费获得积分，订单号: {$order_no}",
                                    'related_id' => $order_no
                                ]);
                            }
                        }
                        
                        // 清空购物车
                        Database::delete('cart_items', 'session_id = ?', [$session_id]);
                        
                        // 提交事务
                        $pdo->commit();
                        
                        // 获取订单信息
                        $order = Database::fetch("SELECT * FROM orders WHERE id = ?", [$order_id]);
                        
                        $order_result = [
                            'success' => true,
                            'message' => '支付成功',
                            'order' => $order
                        ];
                    } catch (Exception $e) {
                        // 回滚事务
                        $pdo->rollback();
                        
                        $order_result = [
                            'success' => false,
                            'message' => '支付失败: ' . $e->getMessage()
                        ];
                    }
                }
            } catch (Exception $e) {
                $order_result = [
                    'success' => false,
                    'message' => '系统错误: ' . $e->getMessage()
                ];
            }
        }
    }
    // 余额支付会员搜索
    else if ($search_type === 'member_search') {
        $phone_search = $_POST['member_phone'] ?? '';
        
        if (!empty($phone_search)) {
            try {
                // 查询条件（手机号或会员账号）
                $where = '';
                $params = [];
                
                // 检查是否为纯数字，如果是则尝试同时查询手机号和会员账号（添加M前缀）
                if (is_numeric($phone_search)) {
                    $username_search = 'M' . $phone_search;
                    $where = "(phone = ? OR username = ?) AND role = 'member'";
                    $params = [$phone_search, $username_search];
                } else {
                    // 如果不是纯数字，只按原值查询
                    $where = "(phone = ? OR username = ?) AND role = 'member'";
                    $params = [$phone_search, $phone_search];
                }
                
                // 查询会员信息
                $member = Database::fetch("SELECT id, name, phone, username, balance, points FROM users WHERE $where", $params);
                
                if ($member) {
                    $member_info = $member;
                } else {
                    $search_error = '未找到该会员';
                }
            } catch (Exception $e) {
                $search_error = '查询会员信息失败: ' . $e->getMessage();
            }
        } else {
            $search_error = '请输入会员手机号或账号';
        }
    }
    // 现金支付会员搜索
    else if ($search_type === 'cash_member_search') {
        $cash_phone_search = $_POST['cash_member_phone'] ?? '';
        
        if (!empty($cash_phone_search)) {
            try {
                // 查询条件（手机号或会员账号）
                $where = '';
                $params = [];
                
                // 检查是否为纯数字，如果是则尝试同时查询手机号和会员账号（添加M前缀）
                if (is_numeric($cash_phone_search)) {
                    $username_search = 'M' . $cash_phone_search;
                    $where = "(phone = ? OR username = ?) AND role = 'member'";
                    $params = [$cash_phone_search, $username_search];
                } else {
                    // 如果不是纯数字，只按原值查询
                    $where = "(phone = ? OR username = ?) AND role = 'member'";
                    $params = [$cash_phone_search, $cash_phone_search];
                }
                
                // 查询会员信息
                $cash_member = Database::fetch("SELECT id, name, phone, username, balance, points FROM users WHERE $where", $params);
                
                if ($cash_member) {
                    $cash_member_info = $cash_member;
                } else {
                    $cash_search_error = '未找到该会员';
                }
            } catch (Exception $e) {
                $cash_search_error = '查询会员信息失败: ' . $e->getMessage();
            }
        } else {
            $cash_search_error = '请输入会员手机号或账号';
        }
    }
}
?>

<div class="container-fluid" id="products-page">
    <!-- 提示消息显示区域 -->
    <div id="alert-container"></div>
    
    <div class="row">
        <div class="col-md-8">
            <!-- 分类切换 -->
            <div class="category-tabs">
                <div class="category-tab active" data-id="all">全部</div>
                <?php foreach ($categories as $category): ?>
                <div class="category-tab" data-id="<?php echo $category['id']; ?>">
                    <?php echo htmlspecialchars($category['name']); ?>
                </div>
                <?php endforeach; ?>
            </div>
            
            <!-- 商品列表 -->
            <div class="products-container">
                <?php if (empty($products)): ?>
                <div class="alert alert-info">暂无商品</div>
                <?php else: ?>
                <?php foreach ($products as $product): ?>
                <div class="product-card" 
                     data-id="<?php echo $product['id']; ?>" 
                     data-name="<?php echo htmlspecialchars($product['name']); ?>" 
                     data-price="<?php echo $product['price']; ?>"
                     data-category-id="<?php echo $product['category_id']; ?>">
                    <?php if (!empty($product['image'])): ?>
                    <img src="<?php echo htmlspecialchars($product['image']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" class="product-image">
                    <?php else: ?>
                    <div class="product-image-placeholder">
                        <i class="fas fa-utensils"></i>
                    </div>
                    <?php endif; ?>
                    <div class="product-name"><?php echo htmlspecialchars($product['name']); ?></div>
                    <div class="product-price">¥<?php echo number_format($product['price'], 2); ?></div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="col-md-4">
            <!-- 购物车 -->
            <div class="cart-section">
                <div class="cart-header">
                    <h5 class="mb-0">购物车</h5>
                    <button id="clear-cart" class="btn btn-sm btn-secondary">
                        <i class="fas fa-trash-alt"></i> 清空
                    </button>
                </div>
                
                <div id="cart-container">
                    <div class="empty-cart">购物车是空的</div>
                </div>
                
                <div class="cart-footer">
                    <div class="cart-total">
                        <span>合计:</span>
                        <span id="cart-total-amount">¥0.00</span>
                    </div>
                    
                    <button id="checkout-btn" class="btn btn-primary btn-lg btn-block">
                        <i class="fas fa-cash-register mr-2"></i> 结账
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 结账模态框 -->
<div class="modal fade" id="checkoutModal" tabindex="-1" role="dialog" aria-labelledby="checkoutModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="checkoutModalLabel">订单结账</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- 显示消息提示区域 -->
                <div id="modal-alerts"></div>
                
                <!-- 支付方式选择 -->
                <div class="payment-methods">
                    <div class="payment-method active" data-type="cash">
                        <div class="payment-method-icon">
                            <i class="fas fa-money-bill-wave"></i>
                        </div>
                        <div>现金支付</div>
                    </div>
                    <div class="payment-method" data-type="balance">
                        <div class="payment-method-icon">
                            <i class="fas fa-wallet"></i>
                        </div>
                        <div>余额支付</div>
                    </div>
                </div>
                
                <!-- 余额支付区域 -->
                <div id="member-payment-section" class="checkout-section" style="display: none;">
                    <h6 class="mb-3">余额支付</h6>
                    <form method="post" action="" id="member-search-form">
                        <input type="hidden" name="search_type" value="member_search">
                        <div class="form-group">
                            <label for="member-phone">会员手机号/会员账号</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="member-phone" name="member_phone" placeholder="输入会员手机号或账号数字" value="<?php echo htmlspecialchars($phone_search); ?>">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" id="member-search-btn">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                            <small class="form-text text-muted">可直接输入手机号或账号数字部分，例如：M163911可输入163911</small>
                        </div>
                    </form>
                    
                    <div id="member-search-result">
                        <?php if ($search_error): ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-circle mr-2"></i> <?php echo htmlspecialchars($search_error); ?>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($member_info): ?>
                        <div id="member-info">
                            <input type="hidden" id="member-info-id" value="<?php echo $member_info['id']; ?>">
                            <div class="alert alert-info">
                                <div><strong>会员:</strong> <?php echo htmlspecialchars($member_info['name']); ?></div>
                                <div><strong>账号:</strong> <?php echo htmlspecialchars($member_info['username']); ?></div>
                                <div><strong>手机:</strong> <?php echo htmlspecialchars($member_info['phone']); ?></div>
                                <div><strong>余额:</strong> ¥<?php echo number_format($member_info['balance'], 2); ?></div>
                                <div><strong>积分:</strong> <?php echo $member_info['points']; ?></div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- 现金支付区域 -->
                <div id="cash-payment-section" class="checkout-section">
                    <h6 class="mb-3">现金支付</h6>
                    <form method="post" action="" id="cash-member-search-form">
                        <input type="hidden" name="search_type" value="cash_member_search">
                        <div class="form-group">
                            <label for="cash-member-phone">会员手机号/会员账号（选填，用于积分）</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="cash-member-phone" name="cash_member_phone" placeholder="输入会员手机号或账号数字" value="<?php echo htmlspecialchars($cash_phone_search); ?>">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" id="cash-member-search-btn">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                            <small class="form-text text-muted">可直接输入手机号或账号数字部分，例如：M163911可输入163911</small>
                        </div>
                    </form>
                    
                    <div id="cash-member-search-result">
                        <?php if ($cash_search_error): ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-circle mr-2"></i> <?php echo htmlspecialchars($cash_search_error); ?>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($cash_member_info): ?>
                        <div id="cash-member-info">
                            <input type="hidden" id="cash-member-info-id" value="<?php echo $cash_member_info['id']; ?>">
                            <div class="alert alert-info">
                                <div><strong>会员:</strong> <?php echo htmlspecialchars($cash_member_info['name']); ?></div>
                                <div><strong>账号:</strong> <?php echo htmlspecialchars($cash_member_info['username']); ?></div>
                                <div><strong>手机:</strong> <?php echo htmlspecialchars($cash_member_info['phone']); ?></div>
                                <div><strong>余额:</strong> ¥<?php echo number_format($cash_member_info['balance'], 2); ?></div>
                                <div><strong>积分:</strong> <?php echo $cash_member_info['points']; ?></div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- 订单备注 -->
                <div class="form-group mt-4">
                    <label for="order-remark">订单备注</label>
                    <textarea class="form-control" id="order-remark" rows="2" placeholder="请输入备注信息"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="complete-payment-btn">完成支付</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 防止被main.js文件的链接覆盖
    // 覆盖全局checkout函数，确保不会跳转到其他页面
    window.checkout = function() {
        // 检查购物车是否为空
        const cartContainer = document.getElementById('cart-container');
        if (cartContainer.querySelector('.empty-cart')) {
            showAlert('购物车为空，无法结账', 'warning');
            return;
        }
        
        // 显示结账模态框
        $('#checkoutModal').modal('show');
    };

    // 产品点击事件 - 添加到购物车
    const productCards = document.querySelectorAll('.product-card');
    productCards.forEach(card => {
        card.addEventListener('click', function() {
            const productId = this.dataset.id;
            const productName = this.dataset.name;
            const productPrice = parseFloat(this.dataset.price);
            
            // 获取当前会话ID
            const sessionId = '<?php echo session_id(); ?>';
            console.log('当前会话ID:', sessionId);
            
            // 优化添加到购物车的请求
            fetch('/api/cart.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({
                    action: 'add',
                    product_id: productId,
                    quantity: 1
                }),
                credentials: 'same-origin' // 确保发送cookies
            })
            .then(response => {
                console.log('响应状态:', response.status);
                if (!response.ok) {
                    return response.text().then(text => {
                        console.error('响应错误:', text);
                        throw new Error('网络响应不正常: ' + response.status);
                    });
                }
                return response.json();
            })
            .then(data => {
                console.log('添加购物车响应:', data);
                if (data.success) {
                    showAlert(`已添加 ${productName} 到购物车`, 'success');
                    loadCart(); // 重新加载购物车
                } else {
                    showAlert(data.message || '添加失败', 'danger');
                }
            })
            .catch(error => {
                console.error('添加到购物车出错:', error);
                showAlert('请求发生错误，请刷新页面重试', 'danger');
            });
        });
    });
    
    // 分类切换
    const categoryTabs = document.querySelectorAll('.category-tab');
    categoryTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有活动状态
            categoryTabs.forEach(t => t.classList.remove('active'));
            
            // 添加当前活动状态
            this.classList.add('active');
            
            const categoryId = this.dataset.id;
            
            // 显示/隐藏商品
            const products = document.querySelectorAll('.product-card');
            products.forEach(product => {
                if (categoryId === 'all' || product.dataset.categoryId === categoryId) {
                    product.style.display = 'block';
                } else {
                    product.style.display = 'none';
                }
            });
        });
    });
    
    // 支付方式切换
    const paymentMethods = document.querySelectorAll('.payment-method');
    const memberPaymentSection = document.getElementById('member-payment-section');
    const cashPaymentSection = document.getElementById('cash-payment-section');
    
    paymentMethods.forEach(method => {
        method.addEventListener('click', function() {
            paymentMethods.forEach(m => m.classList.remove('active'));
            this.classList.add('active');
            
            const paymentType = this.dataset.type;
            
            if (paymentType === 'balance') {
                memberPaymentSection.style.display = 'block';
                cashPaymentSection.style.display = 'none';
            } else {
                memberPaymentSection.style.display = 'none';
                cashPaymentSection.style.display = 'block';
            }
        });
    });
    
    // 购物车加载函数
    function loadCart() {
        console.log('加载购物车...');
        fetch('/api/cart.php?action=get', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Cache-Control': 'no-cache'
            },
            credentials: 'same-origin' // 确保发送cookies
        })
        .then(response => {
            console.log('购物车响应状态:', response.status);
            if (!response.ok) {
                return response.text().then(text => {
                    console.error('购物车响应错误:', text);
                    throw new Error('网络响应不正常: ' + response.status);
                });
            }
            return response.json();
        })
        .then(data => {
            console.log('购物车数据:', data);
            if (data.success) {
                // 更新购物车界面
                updateCartUI(data.items, data.total_amount);
            } else {
                console.error('加载购物车失败:', data.message);
                showAlert('加载购物车失败: ' + (data.message || '未知错误'), 'warning');
            }
        })
        .catch(error => {
            console.error('加载购物车请求失败:', error);
            showAlert('加载购物车失败，请刷新页面重试', 'danger');
        });
    }
    
    // 更新购物车界面
    function updateCartUI(items, totalAmount) {
        const cartContainer = document.getElementById('cart-container');
        const cartTotalAmount = document.getElementById('cart-total-amount');
        
        if (!cartContainer) return;
        
        // 清空购物车容器
        cartContainer.innerHTML = '';
        
        // 检查购物车是否为空
        if (!items || items.length === 0) {
            cartContainer.innerHTML = '<div class="empty-cart">购物车是空的</div>';
            if (cartTotalAmount) {
                cartTotalAmount.textContent = '¥0.00';
            }
            return;
        }
        
        // 创建购物车项容器
        const cartItemsContainer = document.createElement('div');
        cartItemsContainer.className = 'cart-items';
        
        // 添加购物车项
        items.forEach(item => {
            const subtotal = parseFloat(item.price) * parseInt(item.quantity);
            
            const cartItemElement = document.createElement('div');
            cartItemElement.className = 'cart-item';
            cartItemElement.dataset.id = item.id;
            cartItemElement.dataset.productId = item.product_id;
            
            cartItemElement.innerHTML = `
                <div class="cart-item-details">
                    <div class="cart-item-name">${item.product_name}</div>
                    <div class="cart-item-price">¥${parseFloat(item.price).toFixed(2)}</div>
                </div>
                <div class="cart-item-quantity">
                    <button class="quantity-btn decrease" data-id="${item.id}">-</button>
                    <span class="quantity-value">${item.quantity}</span>
                    <button class="quantity-btn increase" data-id="${item.id}">+</button>
                </div>
                <div class="cart-item-subtotal">¥${subtotal.toFixed(2)}</div>
                <button class="cart-item-remove" data-id="${item.id}">
                    <i class="fas fa-times"></i>
                </button>
            `;
            
            cartItemsContainer.appendChild(cartItemElement);
        });
        
        // 添加到购物车容器
        cartContainer.appendChild(cartItemsContainer);
        
        // 更新合计金额
        if (cartTotalAmount) {
            cartTotalAmount.textContent = '¥' + parseFloat(totalAmount).toFixed(2);
        }
        
        // 绑定购物车项事件
        bindCartEvents();
    }
    
    // 绑定购物车项事件
    function bindCartEvents() {
        // 减少数量按钮
        document.querySelectorAll('.cart-item .decrease').forEach(btn => {
            btn.addEventListener('click', function() {
                const itemId = this.dataset.id;
                const quantityElement = this.parentElement.querySelector('.quantity-value');
                let quantity = parseInt(quantityElement.textContent) - 1;
                if (quantity < 1) quantity = 1;
                
                updateCartItemQuantity(itemId, quantity);
            });
        });
        
        // 增加数量按钮
        document.querySelectorAll('.cart-item .increase').forEach(btn => {
            btn.addEventListener('click', function() {
                const itemId = this.dataset.id;
                const quantityElement = this.parentElement.querySelector('.quantity-value');
                let quantity = parseInt(quantityElement.textContent) + 1;
                
                updateCartItemQuantity(itemId, quantity);
            });
        });
        
        // 移除按钮
        document.querySelectorAll('.cart-item-remove').forEach(btn => {
            btn.addEventListener('click', function() {
                const itemId = this.dataset.id;
                removeCartItem(itemId);
            });
        });
    }
    
    // 更新购物车项数量
    function updateCartItemQuantity(itemId, quantity) {
        fetch('/api/cart.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                action: 'update',
                cart_item_id: itemId,
                quantity: quantity
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadCart();
            } else {
                showAlert(data.message || '更新失败', 'danger');
            }
        })
        .catch(error => {
            console.error('更新购物车出错:', error);
            showAlert('请求发生错误', 'danger');
        });
    }
    
    // 移除购物车项
    function removeCartItem(itemId) {
        fetch('/api/cart.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                action: 'remove',
                cart_item_id: itemId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadCart();
            } else {
                showAlert(data.message || '移除失败', 'danger');
            }
        })
        .catch(error => {
            console.error('移除购物车项出错:', error);
            showAlert('请求发生错误', 'danger');
        });
    }
    
    // 清空购物车
    document.getElementById('clear-cart')?.addEventListener('click', function() {
        fetch('/api/cart.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                action: 'clear'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadCart();
                showAlert('购物车已清空', 'success');
            } else {
                showAlert(data.message || '清空失败', 'danger');
            }
        })
        .catch(error => {
            console.error('清空购物车出错:', error);
            showAlert('请求发生错误', 'danger');
        });
    });
    
    // 初始化加载购物车
    loadCart();
    
    // 处理会员搜索 - 余额支付部分
    document.getElementById('member-search-btn')?.addEventListener('click', function() {
        const form = document.getElementById('member-search-form');
        const phoneInput = document.getElementById('member-phone');
        const resultContainer = document.getElementById('member-search-result');
        
        if (!phoneInput.value) {
            showModalAlert('请输入会员手机号或账号', 'warning');
            return;
        }
        
        // 显示加载状态
        resultContainer.innerHTML = '<div class="text-center py-3"><div class="spinner-border text-primary" role="status"><span class="sr-only">搜索中...</span></div><p class="mt-2 text-muted">正在搜索会员...</p></div>';
        
        // 使用FormData获取表单数据
        const formData = new FormData(form);
        
        // 发送AJAX请求
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(html => {
            // 解析返回的HTML
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            
            // 获取会员信息区域
            const memberInfoSection = doc.querySelector('#member-info');
            const errorSection = doc.querySelector('#member-search-result .alert-warning');
            
            // 清空结果容器
            resultContainer.innerHTML = '';
            
            // 如果有错误信息，显示错误
            if (errorSection) {
                resultContainer.appendChild(errorSection.cloneNode(true));
                return;
            }
            
            // 如果有会员信息，显示会员信息
            if (memberInfoSection) {
                resultContainer.appendChild(memberInfoSection.cloneNode(true));
            } else {
                resultContainer.innerHTML = '<div class="alert alert-warning"><i class="fas fa-exclamation-circle mr-2"></i> 未找到该会员</div>';
            }
        })
        .catch(error => {
            console.error('会员搜索失败:', error);
            resultContainer.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle mr-2"></i> 搜索请求失败，请重试</div>';
        });
    });
    
    // 处理会员搜索 - 现金支付部分
    document.getElementById('cash-member-search-btn')?.addEventListener('click', function() {
        const form = document.getElementById('cash-member-search-form');
        const phoneInput = document.getElementById('cash-member-phone');
        const resultContainer = document.getElementById('cash-member-search-result');
        
        if (!phoneInput.value) {
            showModalAlert('请输入会员手机号或账号', 'warning');
            return;
        }
        
        // 显示加载状态
        resultContainer.innerHTML = '<div class="text-center py-3"><div class="spinner-border text-primary" role="status"><span class="sr-only">搜索中...</span></div><p class="mt-2 text-muted">正在搜索会员...</p></div>';
        
        // 使用FormData获取表单数据
        const formData = new FormData(form);
        
        // 发送AJAX请求
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(html => {
            // 解析返回的HTML
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            
            // 获取会员信息区域
            const memberInfoSection = doc.querySelector('#cash-member-info');
            const errorSection = doc.querySelector('#cash-member-search-result .alert-warning');
            
            // 清空结果容器
            resultContainer.innerHTML = '';
            
            // 如果有错误信息，显示错误
            if (errorSection) {
                resultContainer.appendChild(errorSection.cloneNode(true));
                return;
            }
            
            // 如果有会员信息，显示会员信息
            if (memberInfoSection) {
                resultContainer.appendChild(memberInfoSection.cloneNode(true));
            } else {
                resultContainer.innerHTML = '<div class="alert alert-warning"><i class="fas fa-exclamation-circle mr-2"></i> 未找到该会员</div>';
            }
        })
        .catch(error => {
            console.error('会员搜索失败:', error);
            resultContainer.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle mr-2"></i> 搜索请求失败，请重试</div>';
        });
    });
    
    // 完成支付处理 - 直接提交表单，而不是使用API
    document.getElementById('complete-payment-btn')?.addEventListener('click', function(e) {
        e.preventDefault(); // 防止可能的表单提交
        
        const paymentMethod = document.querySelector('.payment-method.active');
        if (!paymentMethod) {
            showModalAlert('请选择支付方式', 'warning');
            return;
        }
        
        const paymentType = paymentMethod.dataset.type;
        let memberId = '';
        
        if (paymentType === 'balance') {
            // 余额支付必须有会员
            const memberInfoElement = document.querySelector('#member-search-result #member-info');
            if (!memberInfoElement) {
                showModalAlert('请先搜索会员并确保会员存在', 'warning');
                return;
            }
            
            const memberInfoId = document.querySelector('#member-search-result #member-info-id');
            if (!memberInfoId) {
                showModalAlert('无法获取会员信息，请重新搜索', 'warning');
                return;
            }
            
            memberId = memberInfoId.value;
            
            // 检查是否有效会员ID
            if (!memberId) {
                showModalAlert('请先搜索有效的会员', 'warning');
                return;
            }
        } else {
            // 现金支付会员是可选的
            const cashMemberInfoId = document.querySelector('#cash-member-search-result #cash-member-info-id');
            if (cashMemberInfoId) {
                memberId = cashMemberInfoId.value;
            }
        }
        
        const remark = document.getElementById('order-remark').value;
        
        // 更新按钮状态，显示加载中
        const payButton = document.getElementById('complete-payment-btn');
        const originalText = payButton.innerHTML;
        payButton.disabled = true;
        payButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';
        
        // 创建表单并直接提交
        const form = document.createElement('form');
        form.method = 'POST';
        form.style.display = 'none';
        
        // 添加字段
        const fields = {
            'search_type': 'checkout',
            'payment_method': paymentType,
            'member_id': memberId,
            'remark': remark
        };
        
        for (const [key, value] of Object.entries(fields)) {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = key;
            input.value = value;
            form.appendChild(input);
        }
        
        document.body.appendChild(form);
        
        fetch('', {
            method: 'POST',
            body: new FormData(form),
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.text())
        .then(html => {
            // 处理返回的HTML
            document.body.removeChild(form);
            
            // 还原按钮状态
            payButton.disabled = false;
            payButton.innerHTML = originalText;
            
            // 解析HTML以获取订单结果
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            
            <?php if ($order_result): ?>
            // 使用PHP生成的订单结果
            const orderResult = <?php echo json_encode($order_result); ?>;
            
            handleOrderResult(orderResult);
            <?php else: ?>
            // 如果没有PHP生成的订单结果，尝试从返回的HTML中解析
            try {
                // 查找脚本中的订单结果
                const scripts = doc.querySelectorAll('script');
                let orderResultFound = false;
                
                for (const script of scripts) {
                    const text = script.textContent;
                    if (text.includes('orderResult')) {
                        // 提取订单结果对象
                        const match = text.match(/const orderResult = (.*?);/);
                        if (match && match[1]) {
                            const orderResult = JSON.parse(match[1]);
                            handleOrderResult(orderResult);
                            orderResultFound = true;
                            break;
                        }
                    }
                }
                
                if (!orderResultFound) {
                    // 尝试查找JSON响应
                    try {
                        const jsonData = JSON.parse(html);
                        if (jsonData && (jsonData.success !== undefined)) {
                            handleOrderResult(jsonData);
                            orderResultFound = true;
                        }
                    } catch (e) {
                        console.error('JSON解析失败:', e);
                    }
                }
                
                if (!orderResultFound) {
                    // 没有找到订单结果，检查是否有错误信息
                    const errorAlert = doc.querySelector('.alert-danger, .alert-warning');
                    if (errorAlert) {
                        showModalAlert(errorAlert.textContent.trim() || '支付失败，请重试', 'danger');
                    } else {
                        showModalAlert('无法处理支付结果，请刷新页面重试', 'warning');
                    }
                }
            } catch (error) {
                console.error('解析订单结果失败:', error);
                showModalAlert('处理订单结果出错，请刷新页面重试', 'danger');
            }
            <?php endif; ?>
        })
        .catch(error => {
            document.body.removeChild(form);
            
            // 还原按钮状态
            payButton.disabled = false;
            payButton.innerHTML = originalText;
            
            console.error('结账失败:', error);
            showModalAlert('网络请求错误，请重试', 'danger');
        });
        
        return false; // 防止事件冒泡和默认行为
    });
    
    // 处理订单结果的通用函数
    function handleOrderResult(orderResult) {
        if (orderResult.success) {
            // 关闭模态框
            $('#checkoutModal').modal('hide');
            
            // 如果WebSocket连接可用，发送订单创建通知
            if (window.posWebSocket && window.posWebSocket.readyState === WebSocket.OPEN) {
                try {
                    const orderMessage = {
                        type: 'order_new',
                        order: orderResult.order
                    };
                    window.posWebSocket.send(JSON.stringify(orderMessage));
                    console.log('已通过WebSocket发送订单创建通知');
                } catch (error) {
                    console.error('发送WebSocket消息失败:', error);
                }
            } else {
                console.warn('WebSocket未连接，无法发送实时通知');
            }
            
            // 显示成功信息
            Swal.fire({
                icon: 'success',
                title: '支付成功',
                text: `订单号: ${orderResult.order.order_no}，取餐号: ${orderResult.order.queue_number}`,
                showConfirmButton: true,
                confirmButtonText: '确定'
            }).then(() => {
                // 重新加载购物车
                loadCart();
            });
        } else {
            showModalAlert(orderResult.message || '支付失败', 'danger');
        }
    }
    
    // 显示普通提示
    function showAlert(message, type) {
        const alertContainer = document.getElementById('alert-container');
        if (!alertContainer) return;
        
        const alertElement = document.createElement('div');
        alertElement.className = `alert alert-${type} alert-dismissible fade show`;
        alertElement.innerHTML = `
            ${message}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        `;
        
        // 添加到容器
        alertContainer.appendChild(alertElement);
        
        // 自动关闭
        setTimeout(() => {
            alertElement.remove();
        }, 3000);
    }
    
    // 显示模态框内提示
    function showModalAlert(message, type) {
        const alertPlaceholder = document.getElementById('modal-alerts');
        if (!alertPlaceholder) return;
        
        const alertElement = document.createElement('div');
        alertElement.className = `alert alert-${type} alert-dismissible fade show`;
        alertElement.innerHTML = `
            ${message}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        `;
        
        // 清空之前的提示
        alertPlaceholder.innerHTML = '';
        
        // 添加到容器
        alertPlaceholder.appendChild(alertElement);
        
        // 自动关闭
        setTimeout(() => {
            alertElement.remove();
        }, 3000);
    }
});
</script>

<?php
// 如果是AJAX请求且有订单结果，则直接输出JSON结果
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && $order_result) {
    header('Content-Type: application/json');
    echo json_encode($order_result);
    exit;
}

// 引入页脚
require_once 'includes/footer.php';
?> 